import Cookies from 'js-cookie';
import { useGlobSetting } from '../../hooks/setting/index';

const { appEnName } = useGlobSetting();

export interface MyCookieAttributes extends Omit<Cookies.CookieAttributes, 'sameSite'> {
  sameSite?: 'strict' | 'lax' | 'none';
}

export class CookieManager {
  private options: MyCookieAttributes;

  constructor(options: MyCookieAttributes = {}) {
    const defaultConfig = {
      expires: this.generateExpiredTimeByHour(),
      secure: true,
      path: `/${appEnName}`,
      sameSite: 'strict',
    };
    this.options = { ...defaultConfig, ...options };
  }

  public set(name: string, value: string, option?: MyCookieAttributes): void {
    Cookies.set(name, value, { ...this.options, ...option });
  }

  public get(name: string): string | undefined {
    return Cookies.get(name);
  }

  public remove(name: string): void {
    Cookies.remove(name, this.options);
  }

  private generateExpiredTimeByHour(count = 2) {
    // 创建当前时间的 Date 对象
    const now = new Date();
    // 将时间加上提前加上8小时，防止UTC时区丢失问题
    return new Date(now.getTime() + (count + 8) * 60 * 60 * 1000);
  }
}
